#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

static void usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " ip  port\n"
              << std::endl;
}

//./tcp_client ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    bool alive = false;
    int sock = 0;
    std::string line;
    while (true)
    {
        if (!alive)
        {
            sock = socket(AF_INET, SOCK_STREAM, 0);
            if (sock < 0)
            {
                std::cerr << "socket error" << std::endl;
                exit(2);
            }

            // 客户端不需要bind,但需要端口号，让操作系统自动选择port

            // 客户端要连接别人的能力
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(serverport);
            server.sin_addr.s_addr = inet_addr(serverip.c_str());

            if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
            {
                std::cerr << "connect error" << std::endl;
                exit(3);
            }
            std::cout << "connect success" << std::endl;
            alive=true;
        }

        std::cout << "请输入# ";
        std::getline(std::cin, line);
        if (line == "quit")
            break;
 
        ssize_t s = send(sock, line.c_str(), line.size(), 0); // 发送消息到服务器
        if (s > 0)
        {
            char buffer[1024];
            int ss = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (ss > 0)
            {
                buffer[ss] = 0;
                std::cout << "server 回显: " << buffer << std::endl;
            }
            else if (ss == 0)
            {
                alive = false;
                std::cout<<"退出1"<<std::endl;
                //break;
                close(sock);
            }
        }
       else
       {
           alive = false;
           std::cout<<"退出2"<<std::endl;
           //break;
           close(sock);
       }
        //  else if (s == 0)
        //  {
        //      break;
        //  }
        //  else
        // {
        //      break;
        //  }
         
    }
    // close(sock);

    return 0;
}
